﻿// <copyright file="PlayersGM.cs" company="Gravity Age Studios">
// Code released under the MIT license (see License.txt).
// </copyright>
// <author>Vicente Cartas Espinel</author>
// <email>vicente.cartas@gmail.com</email>
namespace LightSwitchApplication
{
    using System;
    using LightSwitchApplication.Export;
    using LightSwitchApplication.Import;
    using LightSwitchApplication.UserCode;
    using Microsoft.LightSwitch;
    using Microsoft.LightSwitch.Presentation.Extensions;
    using Microsoft.LightSwitch.Security;

    public partial class PlayersGM
    {
        #region Add/Edit Player

        partial void gridAddAndEditNew_Execute()
        {
            // When adding a new user, it is possible to edit the UserName
            this.FindControl("UserName1").IsEnabled = true;

            var player = this.Collection.AddNew();
            player.Visibility = (int)VisibilityEnum.Public;

            this.FindControl("ModalWindow").DisplayName = "Add Player";
            this.OpenModalWindow("ModalWindow");
        }

        partial void gridEditSelected_CanExecute(ref bool result)
        {
            result = this.Collection.SelectedItem != null;
        }

        partial void gridEditSelected_Execute()
        {
            // When editing a new user, it is not possible to edit the UserName, so we disable the control
            this.FindControl("UserName1").IsEnabled = false;

            this.FindControl("ModalWindow").DisplayName = "Edit Player";
            this.OpenModalWindow("ModalWindow");
        }

        partial void SubmitModalWindow_Execute()
        {
            this.CreateUser();

            this.CloseModalWindow("ModalWindow");
            this.DataWorkspace.ApplicationData.SaveChanges();
        }

        partial void CancelModalWindow_Execute()
        {
            this.CloseModalWindow("ModalWindow");
            this.Collection.SelectedItem.Details.DiscardChanges();
        }

        private void CreateUser()
        {
            UserRegistration user = null;
            string userName = this.Collection.SelectedItem.UserName;
            string realName = this.Collection.SelectedItem.RealName;

            // Check if there is an existing User with this UserName in the DB
            user = this.DataWorkspace.SecurityData.UserRegistrations
                .Where(u => u.UserName.Equals(userName, StringComparison.InvariantCultureIgnoreCase))
                .FirstOrDefault();

            if (user == null) // We are creating a new Player, so create a new User associated with it
            {
                // There wasn't a User with the selected UserName, so create one that will use the Player data
                user = this.DataWorkspace.SecurityData.UserRegistrations.AddNew();
                user.UserName = userName;
                user.FullName = realName;
                user.Password = "changeme/123";

                // Assume new users are Players and try to give them the correct role
                var role = this.DataWorkspace.SecurityData.Roles.
                    Where(r => r.Name.Equals("Player", StringComparison.InvariantCultureIgnoreCase))
                    .FirstOrDefault();

                if (role != null)
                {
                    var assign = new RoleAssignment();
                    assign.Role = role;
                    user.RoleAssignments.Add(assign);
                }
            }
            else // We are editing the Player, or the User already existed, check that Player.RealName and User.FullName are sync'ed
            {
                if (!user.FullName.Equals(realName, StringComparison.InvariantCultureIgnoreCase))
                {
                    user.FullName = realName;
                }
            }

            this.DataWorkspace.SecurityData.SaveChanges();
        }

        #endregion

        #region AddExisting Character

        partial void CharactersAddAndEditNew_Execute()
        {
            this.FindControl("ModalCharacters").DisplayName = "Add existing Character";
            this.OpenModalWindow("ModalCharacters");
        }

        partial void SubmitModalCharacters_CanExecute(ref bool result)
        {
            result = this.CharacterToAddToPlayer != null;
        }

        partial void SubmitModalCharacters_Execute()
        {
            this.CloseModalWindow("ModalCharacters");

            this.Collection.SelectedItem.Characters.Add(this.CharacterToAddToPlayer);
            this.DataWorkspace.ApplicationData.SaveChanges();

            // We have added a Character to the Player, refresh his collection
            this.Characters.Refresh();
        }

        partial void CancelModalCharacters_Execute()
        {
            this.CloseModalWindow("ModalCharacters");
        }

        #endregion

        partial void Import_Execute()
        {
            ImporterHelper.ImportPlayers(this.DataWorkspace, this.Collection);
        }

        partial void Export_Execute()
        {
            Exporter.ExportPlayers(this.Collection);
        }
    }
}
